package genesis.familytree.server.modules.sys.service.impl;

import genesis.familytree.server.common.persistence.Page;
import genesis.familytree.server.common.service.BaseService;
import genesis.familytree.server.common.service.ServiceException;
import genesis.familytree.server.modules.sys.dao.ISysUserDao;
import genesis.familytree.server.modules.sys.entity.SysRole;
import genesis.familytree.server.modules.sys.entity.SysUser;
import genesis.familytree.server.modules.sys.service.ISysRoleService;
import genesis.familytree.server.modules.sys.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 */
@Transactional(readOnly = true)
@Service
public class SysUserServiceImpl extends BaseService implements ISysUserService {

    @Resource private ISysUserDao userDao;
    @Resource private ISysRoleService sysRoleService;

    @Override
    public SysUser getById(int id) {
        return this.userDao.get(id);
    }

    @Override
    public SysUser getByName(String username) {
        return this.userDao.getByName(username);
    }

    @Override
    public Page<SysUser> getPage(int pageNumber, int pageSize, SysUser params) {
        Page<SysUser> page = new Page<>(pageNumber, pageSize);

        params.setPage(page);
        List<SysUser> user = this.userDao.getList(params);
        page.setList(user);

        return page;
    }

    @Transactional(readOnly = false)
    public void saveUser(SysUser sysUser) {
        if (null == sysUser.getId()) {
            userDao.insert(sysUser);
        } else {
            // 清除原用户机构用户缓存
            userDao.update(sysUser);
        }
        if (null != sysUser.getId()) {
            // 更新用户与角色关联
            userDao.deleteUserRole(sysUser);

            List<SysRole> roles = this.sysRoleService.getListByUser(sysUser.getId());

            if (!roles.isEmpty()) {
                userDao.insertUserRole(sysUser);
            } else {
                throw new ServiceException(sysUser.getUsername() + "没有设置角色！");
            }
        }
    }


    @Transactional(readOnly = false)
    public void deleteUser(SysUser sysUser) {
        userDao.delete(sysUser);
    }
}
